package com.test.xmlbean;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;

public class JxbUtil {
	
    public static String convertToXmlUTF8(Object obj, String beforeFix,String endFix) {  
        return convertToXml(obj,"UTF-8",beforeFix,endFix);  
    }  
    
    /**
     * 
     * @param obj
     * @param encoding
     * @param prefix构建前缀信息
     * @param endFix后缀信息
     * @return
     */
    public static String convertToXml(Object obj, String encoding,String prefix ,String endFix) {  
        String result = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
            Marshaller marshaller = context.createMarshaller();  
            
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  //决定是否在转换成xml时同时进行格式化（即按标签自动换行，否则即是一行的xml）
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);   //xml的编码方式
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);  //不用带xml头信息
            StringWriter writer = new StringWriter(); 
            writer.write(prefix);
            marshaller.marshal(obj, writer);  
            writer.write(endFix);
            result = writer.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        return result;  
    }  
    
    
    @SuppressWarnings("unchecked")  
    public static <T> T converyToEntity(String xml, Class<T> c) {  
        T t = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(c);  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            t = (T) unmarshaller.unmarshal(new StringReader(xml));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return t;  
    }  
}
